'use strict';
const fiip = require('fiip');
const Link = fiip.Link;

const startServer = (dev, speed) => {
  const SerialPort = require('serialport');
  const rlink = new Link.Client();
  rlink.type = Link.type.serial;
  rlink.status = Link.status.server;
  rlink.address = dev;
  rlink.port = speed;
  rlink.fd = new SerialPort(dev, { baudRate: speed });
  rlink.send = (data, dataLen, link) => {
    rlink.fd.write(data.slice(0, dataLen));
  };
  rlink.recv = fiip.recv.bind(fiip);

  rlink.fd.on('data', function(data) {
    rlink.recv(data, data.length, rlink);
  });
  rlink.fd.on('error', function(error) {
    console.error('fiip-link-serial/client: error:', error);
  });
  rlink.fd.on('close', () => {
    console.error('fiip-link-serial/client: close');
  });

  return rlink;
};

module.exports = startServer;
